package thread.threadPool;

import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

import static java.lang.Thread.*;

/**
 * A implementation of my own ThreadFactoryBuilder learning from guava ThreadFactoryBuilder
 * which allows setting common useful properties of ThreadFactory.
 * This is a natural application of builder pattern
 */
public final class MyThreadFactoryBuilder {
    private static String namingPrefix;
    private static Integer priority;
    private static  Boolean isDaemon;
    private static ThreadFactory backingThreadFactory = null;
    private static UncaughtExceptionHandler uncaughtExceptionHandler = null;

    static ThreadFactory build() {
        final AtomicLong count = (namingPrefix != null) ? new AtomicLong(0) : null;
        return new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                backingThreadFactory = backingThreadFactory == null ? Executors.defaultThreadFactory() : backingThreadFactory;
                Thread thread = backingThreadFactory.newThread(r);
                if (namingPrefix != null) {
                    thread.setName(format(namingPrefix, count.getAndIncrement()));
                }
                if (isDaemon != null) {
                    thread.setDaemon(isDaemon);
                }
                if (priority != null) {
                    thread.setPriority(priority);
                }
                if (uncaughtExceptionHandler != null) {
                    thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
                }

                return thread;
            }
        };
    }
    private static String format(String format, Object... args) {
        return String.format(Locale.ROOT, format, args);
    }
}
